<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>放大镜</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .container {
        width: 300px;
        height: 300px;
        border: 1px solid #ccc;
        position: relative;
      }
      canvas {
        border: 1px solid #ccc;
      }
      #big-canvas {
        position: absolute;
        left: 320px;
        top: 100px;
        display: none;
      }
      #small-canvas {
        position: absolute;
        opacity: 0.5;
        left: 0;
        top: 0;
        display: none;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <!-- 左侧缩略图 -->
      <canvas id="canvas" width="300px" height="300px"></canvas>
      <!-- 右侧大图 -->
      <canvas id="big-canvas" width="500px" height="500px"></canvas>
      <!-- 小盒子 -->
      <canvas id="small-canvas" width="80px" height="80px"></canvas>
    </div>
    <script>
      const container = document.getElementsByClassName("container")[0];
      const canvas = document.getElementById("canvas");
      const context = canvas.getContext("2d");
      const bigCanvas = document.getElementById("big-canvas");
      const bigContext = bigCanvas.getContext("2d");
      const smallCanvas = document.getElementById("small-canvas");
      const smallContext = smallCanvas.getContext("2d");

      //左侧缩略图
      const img = new Image();
      img.src = "../../assets/images/image-20210812095044739.png";
      img.onload = function () {
        context.drawImage(img, 0, 0, 300, 300);
      };

      //小盒子
      const imgbd = new Image();
      imgbd.src = "";
      imgbd.onload = function () {
        smallContext.drawImage(imgbd, 0, 0, 80, 80);
      };

      container.onmousemove = function (event) {
        //鼠标移进小盒子和右侧大图都显示
        bigCanvas.style.display = "block";
        smallCanvas.style.display = "block";
        // x是开始裁剪图片的位置的横坐标  y是开始裁剪图片的位置的纵坐标
        const x =
          event.pageX - container.offsetLeft - smallCanvas.offsetWidth / 2;
        const y =
          event.pageY - container.offsetTop - smallCanvas.offsetHeight / 2;
        //判断边界
        if (x < 0) {
          x = 0;
        }
        if (x > canvas.offsetWidth - smallCanvas.offsetWidth) {
          x = canvas.offsetWidth - smallCanvas.offsetWidth;
        }
        if (y < 0) {
          y = 0;
        }
        if (y > canvas.offsetHeight - smallCanvas.offsetHeight) {
          y = canvas.offsetHeight - smallCanvas.offsetHeight;
        }
        smallCanvas.style.left = x + "px";
        smallCanvas.style.top = y + "px";
        bigContext.drawImage(canvas, x, y, 80, 80, 0, 0, 500, 500);
      };
      container.onmouseleave = function () {
        bigCanvas.style.display = "none";
        smallCanvas.style.display = "none";
      };
    </script>
  </body>
</html>
